#include <iostream>
#include "xmlwc.h"
#include <expat.h>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <iosfwd>
#include <sstream>
#include <fstream>

void start_tag(void * data, char const * el, char const ** attr)
{
    int * counter = (int *) data;
    int i = 0;
    while(attr[i])
    {
        std::string str(attr[i+1]);
        (*counter) += std::count_if(str.begin(), str.end(), NewWord());
        i += 2;
    }
}

void end_tag(void * data, char const * el)
{
}

void between_tag(void *userData, const XML_Char *s, int len)
{
    int * counter = (int *) userData;
    NewWord new_word;
    for(size_t i = 0; i < len; ++i)
    {
        if(new_word(s[i]))
            ++(*counter);
    }
}

XmlWordCounter::XmlWordCounter(std::string const & file) : WordCounter(file)
{    
}

unsigned XmlWordCounter::count()
{
    if (wasModified())
    {
        std::ifstream f(file_.c_str());
        counter_ = 0;

        XML_Parser parser = XML_ParserCreate("UTF-8");
        XML_SetElementHandler(parser, start_tag, end_tag);
        XML_SetCharacterDataHandler(parser, between_tag);
        XML_SetUserData(parser, &counter_);

        std::stringstream buffer;
        buffer << f.rdbuf();
        f.close();

        XML_Parse(parser, buffer.str().c_str(), buffer.str().size(), 0);
        XML_ParserFree(parser);
    }
    return counter_;
}
